package com.lvmama.pangolin.matchcontroller;
import com.lvmama.pangolin.common.Constant;
import com.lvmama.pangolin.common.StringTools;
import com.lvmama.pangolin.controller.BaseController;
import com.lvmama.pangolin.entity.match.MatchTicketCommodity;
import com.lvmama.pangolin.entity.match.MatchTicketCommodityRel;
import com.lvmama.pangolin.match.service.MatchTicketCommodityRelService;
import com.lvmama.pangolin.match.service.MatchTicketCommodityService;
import com.lvmama.pangolin.util.CommodityMatchUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;

/**
* Created by zhoutianqi on 2017/07/28.
*/
@Controller
@RequestMapping("/match/ticket/commodity/rel")
public class MatchTicketCommodityRelController extends BaseController{
	private Logger logger = Logger.getLogger(getClass());
    @Autowired
    private MatchTicketCommodityRelService matchTicketCommodityRelService;
    @Autowired
    private MatchTicketCommodityService matchTicketCommodityService;
    @Autowired
    private CommodityMatchUtil commodityMatchUtil;
    
    @ResponseBody
    @RequestMapping("/noCommodityMatch")
    public Map<String,String> list(String commodityID,HttpServletRequest request){
    	Map<String,String> resultMap = new HashMap<>();
    	try {
    		MatchTicketCommodity realEntity = matchTicketCommodityService.findById(commodityID);
        	realEntity.setLvCommodityId("无关联");
        	matchTicketCommodityService.update(realEntity);
        	//处理掉关联关系里面可能存在的记录
        	Map<String,String> paramMap = new HashMap<>();
        	paramMap.put("monitorId",realEntity.getMonitorId());
        	paramMap.put("commodityId",realEntity.getCommodityId());
        	paramMap.put("companyCode",realEntity.getCompanyCode());
        	paramMap.put("userId",getCurrentUser(request).getId());
        	paramMap.put("business_code","TICKET");
        	//只有一条数据
        	List<MatchTicketCommodityRel> searchRelItem = matchTicketCommodityRelService.findListByMap(paramMap);
        	if(searchRelItem.size()>0){
        		matchTicketCommodityRelService.deleteByMap(paramMap);
    		}
        	resultMap.put("Success", "无商品关联更新成功");
		} catch (Exception e) {
			resultMap.put("errorMessage", "无商品关联更新失败");
		}
    	return resultMap;
    }
    @RequestMapping("/listLmmCommodity")
    public String list(Model model, @RequestParam(defaultValue = "1") Integer page, MatchTicketCommodity entity,
    		HttpServletRequest request,String lmmCommoditySortType) {
    	Map<String,String> paramMap = new HashMap<>();
    	MatchTicketCommodity realEntity = matchTicketCommodityService.findById(entity.getId());
		paramMap.put("userId", getCurrentUser(request).getId());
		paramMap.put("monitorId", realEntity.getMonitorId());
		paramMap.put("companyCode", Constant.COMMODITY_AUTO_MATCH_LMM_COMPANY_CODE);
        
        //对于已经有关联商品的做特殊处理
        MatchTicketCommodity linkedLMMCommodity = null;
        List<MatchTicketCommodity> lvmmList = null;
        //获取已经关联的lmm商品，再拿别的
        if(StringTools.isValid(realEntity.getLvCommodityId())&&StringTools.isNumeric(realEntity.getLvCommodityId())){
        	paramMap.put("commodityId", realEntity.getLvCommodityId());
        	linkedLMMCommodity = matchTicketCommodityService.findListByMap(paramMap).get(0);
        }
        paramMap.remove("commodityId");
        paramMap.put("refuseCommodityId", realEntity.getLvCommodityId());
        //假设走价格排序，添加进来order by price desc
        if(StringTools.isValid(lmmCommoditySortType)){
        	paramMap.put("priceSortFlag", lmmCommoditySortType);
		}
        //拿到全部非关联商品
		lvmmList = matchTicketCommodityService.findListByMap(paramMap);
		//简单一点，用lmmCommoditySortType是否为空判断走默认名称排序或者价格排序
		if(!StringTools.isValid(lmmCommoditySortType)){
			//调用排序方法对非关联商品排序
			commodityMatchUtil.matchSort(realEntity, lvmmList);

		}else
		{//将价格取出转化为double并进行价格降序排序
			Collections.sort(lvmmList, new Comparator<MatchTicketCommodity>() {
				@Override
				public int compare(MatchTicketCommodity o1, MatchTicketCommodity o2) {
					if(o1==null|| StringUtils.isEmpty(o1.getPrice()))
						return 1;
					if(o2==null|| StringUtils.isEmpty(o2.getPrice()))
						return -1;
					return (int) -(Double.valueOf(o1.getPrice()) - Double.valueOf(o2.getPrice()));
				}
			});
		}
		List<MatchTicketCommodity> currentPageData = getCurrentPageData(page,linkedLMMCommodity,lvmmList);
        PageInfo<MatchTicketCommodity> pageInfo = new PageInfo<MatchTicketCommodity>(lvmmList);
        //设置统一分页信息，因为分页使用统一插件
        dealPageInfo(page,pageInfo,lvmmList,linkedLMMCommodity);
        model.addAttribute("page",pageInfo);
        model.addAttribute("lvmmList",currentPageData);
        //设置竞品名称
        entity.setCommodityName(realEntity.getCommodityName());
        //设置竞品价格
        entity.setPrice(realEntity.getPrice());
        model.addAttribute("paramCommoItem",entity);
        //把当前排序值回传
        model.addAttribute("lmmCommoditySortType",lmmCommoditySortType);
        return "match/matchCommodityLinkPage";
    }
    
    private void dealPageInfo(Integer page, PageInfo<MatchTicketCommodity> pageInfo,
			List<MatchTicketCommodity> lvmmList,MatchTicketCommodity linkedLMMCommodity) {
    	int totalCommodityNumber = linkedLMMCommodity==null?lvmmList.size():(lvmmList.size()+1);
    	//余数计算总页数
    	int extra = totalCommodityNumber%Constant.COMMODITY_AUTO_MATCH_PAGE_SIZE;
    	int pages = totalCommodityNumber/Constant.COMMODITY_AUTO_MATCH_PAGE_SIZE;
    	
    	if(extra!=0){
    		pages++;
    	}
    	pageInfo.setPages(pages);
    	//设置当前页
    	pageInfo.setPageNum(page);
    	//设置总页数
    	
    	//设置当前页是否第一页、最后一页
		pageInfo.setIsFirstPage(page==1?true:false);
    	pageInfo.setIsLastPage(page==pages?true:false);
    	//设置上一页、下一页
    	pageInfo.setNextPage(page+1);
    	pageInfo.setPrePage(page-1);
    	//设置商品总数
    	pageInfo.setTotal(totalCommodityNumber);
    	//设置当前页数据Index
    	int startRow = (page-1)*Constant.COMMODITY_AUTO_MATCH_PAGE_SIZE+1;
    	int endtRow = page*Constant.COMMODITY_AUTO_MATCH_PAGE_SIZE;
    	if(page==pages){
    		endtRow = totalCommodityNumber;
    	}
    	pageInfo.setStartRow(startRow);
    	pageInfo.setEndRow(endtRow);
	}

	private List<MatchTicketCommodity> getCurrentPageData(Integer page, MatchTicketCommodity linkedLMMCommodity,
			List<MatchTicketCommodity> lvmmList) {
    	//从List全部数据中截取当前页需要的数据
    	int startIndex = 0;
    	int endIndex = 0;
    	List<MatchTicketCommodity> resultList = new ArrayList<>();
		if(linkedLMMCommodity==null){
			startIndex = (page-1)*Constant.COMMODITY_AUTO_MATCH_PAGE_SIZE;
			endIndex = page*Constant.COMMODITY_AUTO_MATCH_PAGE_SIZE;
		}else if(page==1){
			//把已经关联的商品放在首位
			resultList.add(linkedLMMCommodity);
			startIndex = (page-1)*Constant.COMMODITY_AUTO_MATCH_PAGE_SIZE;
	    	endIndex = page*Constant.COMMODITY_AUTO_MATCH_PAGE_SIZE-1;
		}else{
			startIndex = (page-1)*Constant.COMMODITY_AUTO_MATCH_PAGE_SIZE-1;
			endIndex = page*Constant.COMMODITY_AUTO_MATCH_PAGE_SIZE-1;
		}
		//最大索引为lvmmList.size
		if(endIndex>lvmmList.size()){
			endIndex = lvmmList.size();
		}
		for(int i=startIndex;i<endIndex;i++){
			if(lvmmList.get(i)!=null){
				resultList.add(lvmmList.get(i));
			}else{break;}
		}
		return resultList;
	}

	@ResponseBody
    @RequestMapping("/commodityMatch")
    public Map<String,String> doCommodityMatch(String dataUUID, String lvmmCommodityID,HttpServletRequest request){
    	Map<String,String> resultMap = new HashMap<String,String>();
    	MatchTicketCommodityRel paramItem = new MatchTicketCommodityRel();
    	try {
    		MatchTicketCommodity realEntity = matchTicketCommodityService.findById(dataUUID);
    		realEntity.setLvCommodityId(lvmmCommodityID);
        	paramItem.setProdId(realEntity.getMonitorId());
        	paramItem.setCommodityId(realEntity.getCommodityId());
        	paramItem.setCompanyCode(realEntity.getCompanyCode());
        	paramItem.setUserId(getCurrentUser(request).getId());
        	paramItem.setBusinessCode("TICKET");
        	MatchTicketCommodityRel searchItem = matchTicketCommodityRelService.findByObject(paramItem);
        	if(searchItem!=null){
    			searchItem.setRelCommodityId(lvmmCommodityID);
        		searchItem.setRelType("1");
        		paramItem.setOperTime(new Date());
        		matchTicketCommodityRelService.update(searchItem);
        	}else{
        		paramItem.setRelCommodityId(lvmmCommodityID);
        		paramItem.setRelType("1");
        		paramItem.setOperTime(new Date());
        		matchTicketCommodityRelService.save(paramItem);
        	}
        	matchTicketCommodityService.update(realEntity);
        	resultMap.put("Success", "关联成功");
		} catch (Exception e) {
			resultMap.put("errorMessage", "关联失败！");
			logger.error("商品自动关联-手动关联失败！");
		}
    	return resultMap;
    }

}
